<script lang="ts">
	import { Any } from '$lib/api/proto/google/protobuf/any';
	import type { UserMsgInfo } from '$lib/api/proto/user_msg_api';
	import {
		AllowJoinRoadmap,
		ApplyJoinRoadmap,
		RecvApplyJoinRoadmap,
		UnkwownData
	} from '$lib/api/proto/user_msg_type_api';
	import ConfirmModal from '$lib/components/modal/ConfirmModal.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { EllipsisVertical } from 'lucide-svelte';
	import moment from 'moment';
	import RecvApplyJoinRoadmapMsg from './RecvApplyJoinRoadmapMsg.svelte';

	const PAGE_SIZE = 20;

	let filterByHasRead = $state(false);

	let totalCount = $state(0);
	let msgList = $state([] as UserMsgInfo[]);
	let curPage = $state(0);
	let removeMsgId = $state('');

	const pageCount = $derived(Math.ceil((totalCount ?? 0) / PAGE_SIZE));

	async function loadMsgList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.userMsgApiClient.list({
				sessionId: userStore.userSession,
				filterByHasRead: filterByHasRead,
				hasRead: false,
				offset: PAGE_SIZE * curPage,
				limit: PAGE_SIZE
			}).response
		);
		totalCount = res.totalCount;
		msgList = res.msgList;
	}

    async function onUpdate(msgId: string) {
        if (userStore.userSession == null) {
			return;
		}
        const tmpList = msgList.slice();
        const index = tmpList.findIndex((item) => item.msgId == msgId);
        if(index == -1){
            return;
        }
        const res = await callApi(appStore.userMsgApiClient.get({
            sessionId:userStore.userSession,
            msgId:msgId,
        }).response);
        if(res.msg != undefined){
            tmpList[index] = res.msg;
        }
        msgList = tmpList;
    }

	async function setHasRead(msgId: string) {
		if (userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.userMsgApiClient.setRead({
				sessionId: userStore.userSession,
				msgId: msgId
			}).response
		);
        await onUpdate(msgId);
        await userStore.syncUnReadMsgCount();
	}

	async function removeMsg() {
		if (userStore.userSession == null || removeMsgId == '') {
			return;
		}
		await callApi(
			appStore.userMsgApiClient.remove({
				sessionId: userStore.userSession,
				msgId: removeMsgId
			}).response
		);
		removeMsgId = '';
		await loadMsgList();
		appStore.addToastMessage({
			level: 'success',
			content: '删除消息成功',
			keepTime: 2000
		});
	}

	$effect(() => {
		loadMsgList();
	});
</script>

{#snippet showApplyJoinRoadmapMsg(msg: ApplyJoinRoadmap)}
	<p>
		您申请了成才路线图<button
			type="button"
			class="btn btn-ghost"
			onclick={() => (window.location.href = `/app/roadmap/map?roadmapId=${msg.roadmapId}`)}
			>{msg.roadmapName}</button
		>的访问权限。
	</p>
{/snippet}

{#snippet showAllowJoinRoadmapMsg(msg: AllowJoinRoadmap)}
	<div>
		您已经可以访问成长路线图<button
			type="button"
			class="btn btn-ghost"
			onclick={() => (window.location.href = `/app/roadmap/map?roadmapId=${msg.roadmapId}`)}
			>{msg.roadmapName}</button
		>了。
	</div>
{/snippet}

<div class="absolute right-[20px] -top-[50px] flex gap-2 items-center">
	<select class="select" bind:value={filterByHasRead}>
		<option value={false}>全部</option>
		<option value={true}>未读</option>
	</select>
</div>

<div class="h-[calc(100vh-110px)] overflow-y-auto">
	{#each msgList as msg}
		<div class="border-2 border-base-300 rounded-box mb-[20px]">
			<div class="flex justify-between bg-base-200 rounded-box p-2">
				<div>
					{moment(Number(msg.timeStamp)).format('YYYY-MM-DD HH:mm:ss')}
				</div>
				<div class="flex gap-2 items-center">
					{#if msg.hasRead}
						<span>已读</span>
					{:else}
						<span class="text-secondary font-bold">未读</span>
					{/if}
					<div class="dropdown dropdown-end">
						<div tabindex="0" role="button" class="btn btn-ghost">
							<EllipsisVertical size={16} />
						</div>
						<ul
							class="menu dropdown-content bg-base-100 rounded-box z-1 w-[160px] p-2 shadow-sm gap-2"
						>
							{#if !msg.hasRead}
								<li>
									<button type="button" class="btn btn-ghost" onclick={() => setHasRead(msg.msgId)}
										>标记为已读</button
									>
								</li>
							{/if}
							<li class="text-error">
								<button
									type="button"
									class="btn btn-ghost"
									onclick={() => (removeMsgId = msg.msgId)}>删除</button
								>
							</li>
						</ul>
					</div>
				</div>
			</div>
			<div class="p-2">
				{#if msg.msgData != undefined}
					{#if Any.contains(msg.msgData, UnkwownData)}
						未知消息
					{:else if Any.contains(msg.msgData, ApplyJoinRoadmap)}
						{@render showApplyJoinRoadmapMsg(Any.unpack(msg.msgData, ApplyJoinRoadmap))}
					{:else if Any.contains(msg.msgData, RecvApplyJoinRoadmap)}
						<RecvApplyJoinRoadmapMsg msg={Any.unpack(msg.msgData, RecvApplyJoinRoadmap)} onChange={()=>onUpdate(msg.msgId)}/>
					{:else if Any.contains(msg.msgData, AllowJoinRoadmap)}
						{@render showAllowJoinRoadmapMsg(Any.unpack(msg.msgData, AllowJoinRoadmap))}
					{/if}
				{/if}
			</div>
		</div>
	{/each}

	{#if pageCount > 1}
		<div class="flex justify-center mt-[20px]">
			<div class="join bg-base-200">
				{#if curPage > 0}
					<button class="join-item btn btn-lg" onclick={() => (curPage = curPage - 1)}
						>上一页</button
					>
				{/if}
				{#if curPage != 0}
					<button
						class="join-item btn btn-lg {curPage == 0 ? 'btn-active' : ''}"
						onclick={() => (curPage = 0)}>1</button
					>
				{/if}
				{#if pageCount > 3 && curPage > 1}
					<button class="join-item btn btn-lg btn-disabled">...</button>
				{/if}
				{#if curPage < pageCount}
					<button class="join-item btn btn-lg btn-active">{curPage + 1}</button>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-lg" onclick={() => (curPage += 1)}>{curPage + 2}</button>
				{/if}
				{#if pageCount - curPage > 4}
					<button class="join-item btn btn-lg btn-disabled">...</button>
				{/if}
				{#if pageCount - curPage > 3}
					<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 2)}
						>{pageCount - 1}</button
					>
				{/if}
				{#if pageCount - curPage > 2}
					<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 1)}
						>{pageCount}</button
					>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-lg" onclick={() => (curPage = curPage + 1)}
						>下一页</button
					>
				{/if}
			</div>
		</div>
	{/if}
</div>

<div class="absolute -left-[10000px]">
	{#if removeMsgId != ''}
		<ConfirmModal
			title="删除消息"
			content="是否删除消息?"
			type="error"
			okName="删除"
			onCancel={() => (removeMsgId = '')}
			onOk={() => removeMsg()}
		/>
	{/if}
</div>
